zz <- file.path("U:","My Documents")
File.Location <- file.path(zz,"BDIdummyeg.txt")
BDIData <- read.table(File.Location,header=T)

#BDIData <- read.table("U:\\My Documents\\BDIdummyeg.txt",stringsasFactors=T,header=T)
BDIData <- data.frame(BDIData)
BDIData$BDI[BDIData$BDI==999] <- NA
BDIData <- na.omit(BDIData) 
attach(BDIData)

library(dplyr)
mapping <- c("Baseline"=1,"Post"=2,"1m"=3,"3m"=4,"Follow-Up"=5)
time2 <- mapping[time]
BDIData <- data.frame(BDIData,time2)
idd <- as.factor(id)
#BDIData$X <- model.matrix(~idd-1)

#fac <- as.factor(sample(1:20,400,replace=TRUE))
#dat$X <- model.matrix(~fac-1)       

library(gam)
library(mgcv)

r1=gam(BDI~(s(time2,4)),family="gaussian")

x <- rnorm(450)
BDIData <- data.frame(BDIData,time2,idd,x)
# random effects gam works fitting a random intercept; you need a continuous predictor like age
# random effects gam would therefore not allow time as a predictor
# reread id as it is overwritten when running earlier gam
r2=gam(BDI~x+s(idd, bs="re"),data=BDIData,family="gaussian")
plot(r2)
r2$fitted.values
plot(r2$fitted.values)
plot(time2,r2$fitted.values)
BDIData <- data.frame(BDIData,r2$fitted.values)
library(ggplot2)
# this works
data <- BDIData
ggplot(data = data, aes(x=x, y=r2$fitted.values)) + geom_line(aes(colour=id))

y <- BDI
BDIData <- data.frame(BDIData,y)
data <- BDIData
ggplot(data = data, mapping = aes(x = x y = y)) +
  geom_point(size = 0.5, alpha = 0.5) +
  geom_smooth(method="gam", formula= y~x+s(idd, bs = "re") )

# this works and is the best one as it plots all 90 profiles of GAM fits with random subject intercept
ggplot(data=BDIData,aes(x=time2,y=r2$fitted.values,group=idd))+
  ggtitle("Trajectories: Raw data") +
  xlab("Time")+
  ylab("Score")+
  geom_line() +
  geom_line(data=BDIData,aes(x=time2,y=r2$fitted.values,group=idd),color="red",size=2)

# this works with coloured plots of predicted BDI form the random intercept GAM for each subject
ggplot(BDIData, aes(x = time2, y = r2$fitted.values, group = idd)) +
    geom_smooth(
        aes(fill = idd, linetype = idd),
        method = NULL,
        level = 0.65,
        color = "black",
        size = 0.3
    ) +
    geom_point(aes(color = idd))

# this also works
r2=gam(BDI~time2+s(idd, bs="re"),data=BDIData,family="gaussian")
# this doesn't with too few covariate combinations
r2=gam(BDI~s(time2)+s(idd, bs="re"),data=BDIData,family="gaussian")

r2=gam(BDIData$BDI~s(BDIData$idd, bs="re")+s(BDIData$time2),family="gaussian")


rm1 <- gam(y ~ s(fac, bs="re"),
           data = dat, method = "ML")